## Chapter 3 (Updated)
## Winter 2023 (reflecting final revisions to chapter)

## Load all libraries 
library(tidyverse)
library(haven)  
library(readxl)
library(janitor)
library(modelsummary)
library(psych) 
library(ggpubr) 
library(ggeffects)
library(panelr) 
library(sensemakr) 
library(lfe) 
library(stargazer) 
library(polycor) 
library(forcats)
library(car) 
library(weights) 
library(stringr)

## Set the working directory 
## Tables/Figures then get set via relative directories in files 
setwd("/Users/mattlevendusky/Library/CloudStorage/Dropbox/Affective Polarization/Book Analyses/Final Analyses")

## Read in the data used in the book and do some preliminary cleaning 
data <- read_dta(file="for_r_for_graphs_y.dta") 

########################################
## Figure 3.1: Distribution of Animus ##
######################################## 

## distribution by party  
p2 <- data %>% 
  filter(year == 1) %>%
  filter(!is.na(apstable) & !is.na(dem)) %>% 
  ggplot(aes(apstable, group = dem)) + 
  geom_density(aes(lty = as.factor(dem))) + 
  scale_linetype_manual(name = "",
                        values = c("solid","dashed"),
                        labels = c("Republicans","Democrats")) + 
  xlab("Animus") +
  ylab("Proportion") + 
  #ylim(c(1,4)) + 
  #ggtitle("Distribution of Animus by Party") + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        #legend.position = c(.85,.90), 
        legend.position = "none",
        panel.grid = element_blank())  

## distribution overall 
p1 <- data %>% 
  filter(year == 1) %>%
  filter(!is.na(apstable) & !is.na(dem)) %>% 
  ggplot(aes(apstable)) + 
  geom_density() + 
  xlab("Animus") +
  ylab("Proportion") + 
  #ylim(c(1,4)) + 
  #ggtitle("Overall Distribution of Animus") + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        legend.position = "none", 
        panel.grid = element_blank())   

## add them to one panel 
pdf(file="Figures/Druckman_etal_figure_3_1.pdf",
    height = 8.5,
    width = 11)
print(ggarrange(p1,p2,nrow=1,ncol=2))
dev.off() 

## means/sds by party 
data %>% 
  filter(year == 1) %>%
  filter(!is.na(apstable) & !is.na(dem)) %>% 
  group_by(dem) %>% 
  summarise(avg = mean(apstable),
            sd = sd(apstable)) 

##########################################
## Figure 3.2: Animus & Party Switching ##
########################################## 

## note that this comes before all of the other cleaning 
data <- data %>% 
  mutate(party_switcher = case_when(
    partyid_w1 < 4 & partyid_w4 < 4 ~ 0,
    partyid_w1 > 4 & partyid_w4 > 4 ~ 0,
    partyid_w1 > 4 & partyid_w4 < 4 ~ 1,
    partyid_w1 < 4 & partyid_w4 > 4 ~ 1)) 
ap_quantiles <- quantile(data$apstable, probs=c(0.05,0.10,0.33,0.5,0.67,0.90,0.95), na.rm=T)  

pdf(file="Figures/Druckman_et_al_Figure_3_2.pdf",
    height = 11,
    width = 8.5)
data %>% 
  ggplot(aes(x = apstable, y = 100*party_switcher)) + 
  geom_smooth(color = "black", method = "gam") + 
  #ylim(c(0,35)) + 
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) +
  xlab("Animus") + 
  ylab("Proportion of Party Switchers") + 
  #ggtitle("Party Switching & Animus") +  
  geom_hline(yintercept = 0, lty = 2) + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank())  
dev.off() 

###########################################
## Figure 3.3: 2020 Vote Choice & Animus ##
########################################### 

pdf(file = "Figures/Druckman_et_al_Figure_3_3.pdf",
    height = 11,
    width = 8.5)
data %>% 
  mutate(vote_biden = ifelse(w7whovoted2020 == 1,1,0)) %>%  
  ## split by party (some more defect from high animus Rs)
  ggplot(aes(x = apstable, y = 100*vote_biden)) + 
  geom_smooth(aes(color=as.factor(rep)),
              method = 'gam',
              se = T) + 
  scale_color_manual(name = "",
                     values = c("black","grey70"), 
                     labels = c("Democrat","Republican")) + 
  ylab("Percentage Voting for Biden") + 
  xlab("Animus") + 
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  ylim(c(0,100)) + 
  #ggtitle("Vote for Biden by Animus and Party") + 
  #labs(lty = "") + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) 
dev.off() 

###############################################
## Figure 3.4: Stability of Animus Over Time ##
############################################### 

## add in other cleaning 
## Pure Independents 
data <- data %>% 
  mutate(pure_ind = ifelse(partyid_w1 == 4 & 
                             partyid_w3 == 4 & partyid_w4 == 4,1,0)) 
## roughly 5% of the sample 

## Party Switchers 
## can change strength, but can't go D --> R or R --> D 
data <- data %>% 
  mutate(party_switcher = case_when(
    partyid_w1 < 4 & partyid_w4 < 4 ~ 0,
    partyid_w1 > 4 & partyid_w4 > 4 ~ 0,
    partyid_w1 > 4 & partyid_w4 < 4 ~ 1,
    partyid_w1 < 4 & partyid_w4 > 4 ~ 1)) 
## roughly 6% of the sample 

## People in Condition 13 
data <- data %>% 
  mutate(c13 = ifelse(condition2 == 13,1,0)) 

## Remove these people from the sample 
data <- data %>% 
  filter(pure_ind == 0 & party_switcher == 0 | c13 == 0) 

## add quantiles for graphs 
ap_quantiles <- quantile(data$apstable, probs=c(0.05,0.10,0.33,0.5,0.67,0.90,0.95), na.rm=T) 
## small quantiles for busier graphs 
ap_quantiles_small <- quantile(data$apstable, probs=c(0.05,0.33,0.67,0.95), na.rm=T) 

## Remove the top and bottom 5% from the sample 
## removes weird-non-linearities from odd folks 
data <- data %>% 
  filter(apstable > ap_quantiles[1] & 
           apstable < ap_quantiles[7]) 

## For faceting graphs: year as a factor variable 
data$factor_year <- factor(data$year,
                           labels = c("July 2019",
                                      "April 2020",
                                      "October 2020",
                                      "April 2021")) 


## feeling thermometer graph 
pdf(file = "Figures/Extra/Over_Time_Stability_in_Feeling_Thermometers.pdf",
    height = 8.5,
    width = 11)
print(data %>% 
        select(c(year,ftout,ftin)) %>% 
        pivot_longer(cols = c(ftout,ftin),
                     names_to = "group",
                     values_to = "eval") %>% 
        group_by(year,group) %>% 
        summarise(ftbar = 100*mean(eval, na.rm=T)) %>% 
        mutate(inout_label = factor(group,
                                    levels = c("ftin","ftout"),
                                    labels = c("In-Party","Out-Party"))) %>% 
        ggplot(aes(x = year, y = ftbar)) + 
        geom_line() + 
        ylim(c(0,100)) + 
        scale_x_continuous(breaks = c(1:4),
                           limits = c(1,4),
                           labels = c("July \n 2019","April \n 2020",
                                      "October \n 2020", "April \n 2021")) + 
        xlab("") + 
        ylab("FT Score") + 
        ggtitle("Over-Time Party Feeling Thermometers") + 
        theme_bw() + 
        theme(plot.title = element_text(hjust=0.5),
              legend.position = "none", 
              panel.grid = element_blank()) + 
        facet_grid(cols = vars(inout_label))) 
dev.off() 

pdf(file = "Figures/Druckman_et_al_Figure_3_4.pdf",
    height = 11,
    width = 8.5)
data %>% 
  filter(year == 4) %>%
  filter(!is.na(apstable) & !is.na(affpol)) %>% 
  ggplot(aes(apstable,affpol)) + 
  geom_point(color="grey",alpha=0.8) +  
  geom_smooth(method="lm",color="black", se=F) + 
  geom_abline(slope = 1, intercept = 0, 
              lty = 2, color = "darkgrey") + 
  xlim(c(0.2,0.9)) + 
  ylim(c(0.2,0.9)) + 
  xlab("July 2019 Animus") +
  ylab("April 2021 Animus") + 
  #ylim(c(1,4)) + 
  #ggtitle("Animus over Time") + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank())
dev.off() 

## Heise Stability Coefficients 
data %>% 
  select(ftout,ftin,uniqueid,year) %>% 
  panel_data(., id = uniqueid, wave = year) %>% 
  heise(.,ftout,ftin) 


## feeling thermometer correlations 
cor(data$ftout[data$year==1],data$ftout[data$year==2],use="pairwise")
cor(data$ftout[data$year==1],data$ftout[data$year==3],use="pairwise")
cor(data$ftout[data$year==1],data$ftout[data$year==4],use="pairwise")

## full measure correlation 
cor(data$apstable[data$year==1],data$affpol[data$year==4],use="pairwise")

#############################################
## Figure 3.5: Animus & Political Identity ##
############################################# 

## calculate strong partisan, strong ideologue, sorted 
data <- data %>% 
  mutate(
    strong_partisan = ifelse(partyid_w1 == 1 | partyid_w1 == 7,1,0),
    strong_ideologue = ifelse(wave1ideology == 1 | wave1ideology == 7,1,0),
    sorted = ifelse((partyid_w1 < 4 & wave1ideology < 4) | (partyid_w1 > 4 & wave1ideology >4),
                    1,0)) %>% 
  rowwise() %>% 
  mutate(sociden_pid = mean(c(party_importance,party_describe,party_wethey,party_extent),
                            na.rm=T)) %>% 
  ungroup() 
## do top 25% of social identity scale 
data$hi_sid_pid <- ifelse(data$sociden_pid>3.74,1,0) 

## correlation between measures and animus 
cor(data$sociden_pid[data$year==1],data$apstable[data$year==1],use="pairwise") ## 0.15
polychor(data$strong_partisan[data$year==1],data$apstable[data$year==1]) ## 0.18 
polychor(data$strong_ideologue[data$year==1],data$apstable[data$year==1]) ## 0.21 
polychor(data$sorted[data$year==1],data$apstable[data$year==1]) ## 0.19 


## pivot wide to long then plot 
pdf(file = "Figures/Druckman_et_al_Figure_3_5.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(strong_partisan,sorted,hi_sid_pid,apstable)) %>% 
  pivot_longer(cols = c(strong_partisan,sorted,hi_sid_pid),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## label the factor for plotting 
  mutate(identity_factor = factor(plotvar,
                                  levels = c("strong_partisan","sorted","hi_sid_pid"),
                                  labels = c("Strong Partisan",
                                             "Sorted",
                                             "High Partisan Social Identity"))) %>% 
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(color = "black",
              se = T) + 
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Political Identity and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(identity_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) + 
  guides(linetype=guide_legend(nrow=2,byrow=TRUE))
dev.off() 

###################################
## Figure 3.6: Ideology & Animus ##
################################### 

# Creating measure of ideology based on policy positions
policy_pca <- data %>%
  select(soc_sec_spending, healthcare, services_spending, gov_role,
         abortion, homosexual_protection, mmigration, trans_protection) %>%
  na.omit() %>%
  prcomp(scale. = TRUE,
         center = TRUE)
summary(policy_pca) # pretty indicative data is mostly on one dimension

# Adding policy liberalism measure to data set
data <- data %>%
  filter(!is.na(soc_sec_spending) & !is.na(healthcare) & !is.na(services_spending) & 
           !is.na(gov_role) & !is.na(abortion) & !is.na(homosexual_protection) &
           !is.na(mmigration) & !is.na(trans_protection)) %>%
  mutate(conservatism = scales::rescale(-policy_pca$x[,1])) 

## Fold scale so that it's ideological extremity 
data$fold_policy <- abs(data$conservatism - 0.5) 

## top 25% of extremity 
data$extreme <- ifelse(data$fold_policy > 0.3,1,0) 

## pivot wide to long then plot 
pdf(file = "Figures/Druckman_et_al_Figure_3_6.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(strong_ideologue,extreme,apstable)) %>% 
  pivot_longer(cols = c(strong_ideologue,extreme),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## label the factor for plotting 
  mutate(identity_factor = factor(plotvar,
                                  levels = c("extreme","strong_ideologue"),
                                  labels = c("Issue Extremity",
                                             "Strong Ideologue"))) %>% 
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(color = "black",
              se = T) + 
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Issue Extremity and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(identity_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) 
dev.off() 

#####################################
## Figure 3.7: Animus & Engagement ##
##################################### 

data <- data %>% 
  mutate(
    freq_talk = ifelse(talk_freqwave3 ==3,1,0),
    freq_sm = ifelse(social_freqwave3 ==3,1,0),
    high_interest = ifelse(political_interest > 3,1,0),
    correct_veto = ifelse(p_knowledge_veto==4,1,0),
    correct_house = ifelse(p_knowledge_hofr==1,1,0),
    correct_law = ifelse(p_knowledge_constitution == 3,1,0),
    correct_vp = ifelse(p_knowledge_vp==3,1,0),
    correct_party = ifelse(p_knowledge_conservative==2,1,0)) %>% 
  rowwise() %>% 
  mutate(knowledge = sum(c(correct_veto,correct_house,correct_law,
                           correct_vp,correct_party),na.rm=T)) %>% 
  ungroup() 
## get 4 or 5 (out of 5) right 
data$hi_knowledge <- ifelse(data$knowledge>3.99,1,0)


pdf(file="Figures/Druckman_et_al_Figure_3_7.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(apstable,freq_talk,freq_sm,high_interest,hi_knowledge)) %>% 
  pivot_longer(cols = c(freq_talk,freq_sm,high_interest,hi_knowledge),
               names_to = "plotvar",
               values_to = "value") %>%  
  mutate(engagement_factor = factor(plotvar,
                                    levels = c("freq_talk",
                                               "freq_sm",
                                               "high_interest",
                                               "hi_knowledge"),
                                    labels = c("Freq. of Political Discussion",
                                               "Freq. of Social Media Use",
                                               "High Political Interest",
                                               "High Political Knowledge"))) %>%  
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(color = "black",
              se = T) + 
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Political Engagement, Knowledge, and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(engagement_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "bottom", 
        panel.grid = element_blank()) + 
  guides(linetype=guide_legend(nrow=2,byrow=TRUE))
dev.off() 

###########################################
## Figure 3:8 Demographics #1 and Animus ##
########################################### 

## need a helper function to correctly label the levels of party ID 
data$party_factor <- factor(data$dem,
                            levels =c(0:1),
                            labels = c("Republicans","Democrats")) 

data <- data %>% 
  mutate(college = ifelse(education > 4,1,0),
         rich = ifelse(income > 3,1,0),
         christian = ifelse(religion == 1 | religion == 2,1,0),
         not_relig = ifelse(religion == 7,1,0))  

## christian needs to grab everyone who says "Christian" in other 
library(stringr) 
data <- data %>% 
  mutate(other_christian = ifelse(str_detect(str_to_lower(religion_other),"unit|true|latter|bap|southern|seventh|orthodox|prod|pentec|non-de|non de|mormon|meth|luth|lds|jesus|jeh|chris|cris|evang|epis|cath|born|ana"),
                                  1,0))

## combine closed & open-ended responses 
data <- data %>% 
  mutate(full_christian = ifelse(christian == 1 | other_christian == 1,1,0)) 

## plot 
pdf(file = "Figures/Druckman_et_al_Figure_3_8.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1 & !is.na(dem)) %>% 
  select(c(apstable,dem,college,rich,full_christian)) %>% 
  pivot_longer(cols = c(college,rich,full_christian),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## make labels for the plot 
  mutate(demog_factor = factor(plotvar, 
                               levels = c("college",
                                          "rich",
                                          "full_christian"), 
                               labels = c("College-Educated",
                                          "Wealthy",
                                          "Christian"))) %>%  
  ggplot(aes(x = apstable, y = 100*value, group = dem)) + 
  geom_smooth(aes(color = as.factor(dem),
                  fill = as.factor(dem)), 
              method = "gam",
              se = T) + 
  scale_color_manual(name = "",
                     values = c("grey70","black"), 
                     labels = c("Republicans","Democrats")) + 
  scale_fill_manual(name = "",
                    values = c("grey70","black"), 
                    labels = c("Republicans","Democrats")) +   
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Education, Income, Religion, and Animosity") + 
  #labs(lty = "") + 
  theme_bw() +  
  facet_grid(cols = vars(demog_factor)) +   
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) + 
  guides(linetype=guide_legend(nrow=2,byrow=TRUE))
dev.off()



##########################################
## Figure 3.9: Demographics #2 & Animus ##
########################################## 
## second set of demographics 
data <- data %>% 
  mutate(white = ifelse(race ==1,1,0),
         over50 = ifelse(age > 4,1,0),
         female = ifelse(gender == 2,1,0)) 

pdf(file = "Figures/Druckman_et_al_Figure_3_9.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(partyid_w1 != 4 & partychange == 0 & year == 1) %>% 
  pivot_longer(cols = c(white,over50,female),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## make labels for the plot 
  mutate(demog_factor = factor(plotvar, 
                               levels = c("white","over50","female"), 
                               labels = c("White",
                                          "Over 50",
                                          "Female"))) %>%
  ggplot(aes(x = apstable, y=100*value)) + 
  geom_smooth(aes(color = as.factor(dem),
                  fill = as.factor(dem)),
              method="gam",
              se = T) + 
  scale_color_manual(name = "",
                     values = c("grey70","black"), 
                     labels = c("Republicans","Democrats")) + 
  scale_fill_manual(name = "",
                    values = c("grey70","black"), 
                    labels = c("Republicans","Democrats")) +   
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Race, Age, Gender, and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(demog_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank())
dev.off() 

#########################################################
## For Appendix: Figures 3.5 - 3.7 Separately by Party ##
######################################################### 

## Figure 3.5 by party 
pdf(file = "Figures/Druckman_et_al_Figure_3_5_By_Party_for_Appendix.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(strong_partisan,sorted,hi_sid_pid,apstable,dem)) %>% 
  pivot_longer(cols = c(strong_partisan,sorted,hi_sid_pid),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## label the factor for plotting 
  mutate(identity_factor = factor(plotvar,
                                  levels = c("strong_partisan","sorted","hi_sid_pid"),
                                  labels = c("Strong Partisan",
                                             "Sorted",
                                             "High Partisan Social Identity"))) %>% 
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(aes(color = as.factor(dem),
                  fill = as.factor(dem)),
              method="gam",
              se = T) + 
  scale_color_manual(name = "",
                     values = c("grey70","black"), 
                     labels = c("Republicans","Democrats")) + 
  scale_fill_manual(name = "",
                    values = c("grey70","black"), 
                    labels = c("Republicans","Democrats")) +  
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Political Identity and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(identity_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) + 
  guides(linetype=guide_legend(nrow=2,byrow=TRUE))
dev.off() 

## Figure 3.6 by Party 
pdf(file = "Figures/Druckman_et_al_Figure_3_6_By_Party_For_Appendix.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(strong_ideologue,extreme,apstable,dem)) %>% 
  pivot_longer(cols = c(strong_ideologue,extreme),
               names_to = "plotvar",
               values_to = "value") %>% 
  ## label the factor for plotting 
  mutate(identity_factor = factor(plotvar,
                                  levels = c("extreme","strong_ideologue"),
                                  labels = c("Issue Extremity",
                                             "Strong Ideologue"))) %>% 
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(aes(color = as.factor(dem),
                  fill = as.factor(dem)),
              method="gam",
              se = T) + 
  scale_color_manual(name = "",
                     values = c("grey70","black"), 
                     labels = c("Republicans","Democrats")) + 
  scale_fill_manual(name = "",
                    values = c("grey70","black"), 
                    labels = c("Republicans","Democrats")) +  
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Issue Extremity and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(identity_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) 
dev.off() 

## Figure 3.7 by Party 
pdf(file="Figures/Druckman_et_al_Figure_3_7_By_Party_For_Appendix.pdf",
    height = 8.5,
    width = 11)
data %>% 
  filter(year == 1) %>% 
  select(c(apstable,freq_talk,freq_sm,high_interest,hi_knowledge,dem)) %>% 
  pivot_longer(cols = c(freq_talk,freq_sm,high_interest,hi_knowledge),
               names_to = "plotvar",
               values_to = "value") %>%  
  mutate(engagement_factor = factor(plotvar,
                                    levels = c("freq_talk",
                                               "freq_sm",
                                               "high_interest",
                                               "hi_knowledge"),
                                    labels = c("Freq. of Political Discussion",
                                               "Freq. of Social Media Use",
                                               "High Political Interest",
                                               "High Political Knowledge"))) %>%  
  ggplot(aes(x = apstable, y = 100*value)) + 
  geom_smooth(aes(color = as.factor(dem),
                  fill = as.factor(dem)),
              method="gam",
              se = T) + 
  scale_color_manual(name = "",
                     values = c("grey70","black"), 
                     labels = c("Republicans","Democrats")) + 
  scale_fill_manual(name = "",
                    values = c("grey70","black"), 
                    labels = c("Republicans","Democrats")) +  
  scale_x_continuous(breaks = ap_quantiles, 
                     labels = c("5th \n pct","10th \n pct","33rd \n pct","50th \n pct","67th \n pct", "90th \n pct","95th \n pct")) + 
  xlab("Animus") +
  ylab("Percentage of Respondents") +
  ylim(c(0,100)) + 
  #ggtitle("Political Engagement, Knowledge, and Animosity") + 
  #labs(lty = "") + 
  theme_bw() + 
  facet_grid(cols = vars(engagement_factor)) + 
  theme(plot.title = element_text(hjust=0.5),
        legend.position = "none", 
        panel.grid = element_blank()) + 
  guides(linetype=guide_legend(nrow=2,byrow=TRUE))
dev.off() 
